package com.jihox.abookpro;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import com.igexin.sdk.PushManager;
import com.jihox.abookpro.R;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.model.CustomerInfo;
import com.jihox.abookpro.model.ThirdCustomerInfo;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.MyTextWatcher;
import com.jihox.abookpro.view.JHProgressDialog;
import com.jihox.abookpro.R.drawable;



/**
 * Created by york.gui on 15-6-17.
 * 登录活动
 * 输入手机号，密码登录账户
 * 点击注册进去注册页面
 * 点击找回密码，进去重置密码页面
 * 利用第三方账户登录
 */
public class LoginActivity extends BaseActivity implements PlatformActionListener{	
	
	private static final int REQUEST_TIMEOUT = 100*1000;//设置请求超时10秒钟  
	private static final int SO_TIMEOUT = 100*1000;  //设置等待数据超时时间10秒钟
	private static final String SHAREDPREFERENCES_CUSTOMERINFO = "CUSTOMER_TOKEN";
	private static final String ORDERACTIVITY = "orderactivity";
	private static final String HOMEFRAGMENT = "homefragment";
	private static final int REGIST_CODE = 1234321;
	
	private static final int MSG_SMSSDK_CALLBACK = 1;
	private static final int MSG_AUTH_CANCEL = 2;
	private static final int MSG_AUTH_ERROR= 3;
	private static final int MSG_AUTH_COMPLETE = 4;
	private static final int GO_LOGIN = 5;
	private static final int PROXYTYPE_WX = 1;
	private static final int PROXYTYPE_QQ = 2;
	private static final int PROXYTYPE_SINA = 3;

	//第三方登录的相关

//	private final String WeiXinAppid=ConfigProperties.getWXAppId();
//	private IWXAPI api; 
//	private final String SINA_APP_KEY=ConfigProperties.getSinaAppId();
//	boolean isFrontiaInit = false;//Frontia是否初始化成功
//	private int proxyFlag = 0;
//	private String uid = null;
//	private String accessToken = null;
//	//百度授权模块实例
//	private FrontiaAuthorization mAuthorization;
//    
    private EditText phoneNumber;
    private Button resetPhoneNumber;
    private EditText passWord;
    private Button resetPassword;
    private Button passwordVisible;
    private Button login;
    private Button forgotPassword;
    private Button weixinProxy;
    private Button qqProxy;
    private Button weiboProxy;
    
    private CustomerInfo customerInfo = new CustomerInfo();
    private ThirdCustomerInfo thirdCustomerInfo = new ThirdCustomerInfo();
    private String clientId;
    
    private String come;
    private  Intent comeintent;
    
    private JHProgressDialog pd;
    
    private boolean passwordIsHidden = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        //comefrom
        comeintent = getIntent();
        if(null!=comeintent){
        	come = comeintent.getStringExtra("comefrom");
        }
        
        //initial ShareSDK
      	ShareSDK.initSDK(this);
      	ShareSDK.removeCookieOnAuthorize(true);//web授权时自动清空cookie
        initView();//初始化控件
        initHeader();//初始化header     
        
        
        //清空按钮是否显示
        phoneNumber.addTextChangedListener(new MyTextWatcher(resetPhoneNumber));
        passWord.addTextChangedListener(new MyTextWatcher(resetPassword));
       
        /**
         * 清空已输入的手机号,重新输入号码
         */
        resetPhoneNumber.setOnClickListener(new View.OnClickListener() {
        	
            @Override
            public void onClick(View view) {
                phoneNumber.setText(null);
            }
        });
        /**
         * 清空已输入的密码，重新输入密码
         */
        resetPassword.setOnClickListener(new View.OnClickListener() {
        	
            @Override
            public void onClick(View view) {
                passWord.setText(null);
            }
        });
        /**
         * 点击可见按钮，使密码可见或隐藏
         */
        passwordVisible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (passwordIsHidden) {
	                passWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
	                passwordVisible.setBackgroundResource(drawable.visible_filled_off);
                }else {
                    passWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    passwordVisible.setBackgroundResource(drawable.visible_filled_on);
                }
                passwordIsHidden = !passwordIsHidden;
            }
        });
        
        login.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("null")
			@Override
            public void onClick(View view) {
                //TODO 将手机号密码已Post方式提交到服务器，验证登录
            	/**获取客户手机号和密码
            	 * 做简单的手机号格式验证
            	 */
            	//获取手机号码
            	customerInfo = new CustomerInfo();
            	String phoneNo = phoneNumber.getText().toString().trim();
            	if(phoneNo != null && !phoneNo.equals("")){
	                Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
	                Matcher m = p.matcher(phoneNo);
	                if ( m.matches()) {
	                    customerInfo.setPhoneNo(phoneNo);                 
	                    //获取密码
	                    String cstPassword = passWord.getText().toString().trim();
	                    if (cstPassword != null && !cstPassword.equals("")) {
	                    	customerInfo.setCstPassword(cstPassword);
	                    	MyApplication.getInstance().setUserId(phoneNo);
	                    	//向服务器请求登录,非第三方登录        
	                    	login(false);
	                    } else {
	                    	Toast.makeText(LoginActivity.this, R.string.T_No_Password, Toast.LENGTH_SHORT).show();
	                    }
	                }else {
	                    Toast.makeText(LoginActivity.this, R.string.T_Phone_Format_Error, Toast.LENGTH_SHORT).show();
	                }
            	}else{
            		Toast.makeText(LoginActivity.this, R.string.T_No_PhoneNumber, Toast.LENGTH_SHORT).show();
            	}
            }
        });
        

        /**
         * 向服务器提交手机号和密码，请求登录
         */            	       
        
        //重置密码
        forgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, ForgotPassWordActivity.class);
                startActivity(intent);
            }
        });
        //使用微信登录
        weixinProxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	//TODO 微信登录
            	Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
            	boolean wechat_isclientvalid = wechat.isClientValid();
            	if(!wechat_isclientvalid){	
            		Toast.makeText(LoginActivity.this, R.string.wx_not_found, Toast.LENGTH_SHORT).show();
            	}else{
            		thirdCustomerInfo.setProxyType(PROXYTYPE_WX);
            		authorize(wechat);
            	}
            }
        });
        //使用QQ登陆
        qqProxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	//TODO QQ登录
            	Platform qq = ShareSDK.getPlatform(QQ.NAME);
            	thirdCustomerInfo.setProxyType(PROXYTYPE_QQ);
				authorize(qq);
            }
        });
        //使用新浪微博登录
        weiboProxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 
            	//TODO 新浪微博登录
            	Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
            	thirdCustomerInfo.setProxyType(PROXYTYPE_SINA);
				authorize(sina);
            }
        });
    } 
    
    //执行授权,获取用户信息
  	private void authorize(Platform plat) {
  		if (plat.isValid()) {//判断是否已经授权，如果已授权则删除授权，重新授权
  			plat.removeAccount();
  		} 		
  		//SSO授权
  		plat.SSOSetting(false);
  		plat.setPlatformActionListener(this);
  		plat.authorize(); 
  	}
    private void login(boolean isThrid) {
    	//提示正在登录    	
	    	pd = JHProgressDialog.show(LoginActivity.this, null,
					getResources().getString(R.string.T_Logining_short));
				new Thread(new loginRunnable(isThrid)).start();
			
	}
    /**
     * 先服务器提交登录请求进程
     */
    private  class loginRunnable implements Runnable{
    	  boolean isThrid;
    	  private loginRunnable(boolean isThrid){
    		this.isThrid = isThrid;
    	  }
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			//设置连接超时时间
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			HttpClient httpClient = new DefaultHttpClient(httpParams);
			HttpPost httpPost = new HttpPost();
			ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();			
			//取得登录地址
			
			if(!isThrid){//添加非第三方登录传递数据
				httpPost = new HttpPost(
					ConfigProperties.getLoginUrl());
				paramsList.add(new BasicNameValuePair("phoneNo", customerInfo.getPhoneNo()));
				paramsList.add(new BasicNameValuePair("cstPassword", customerInfo.getCstPassword()));
				UserHelper helper = new UserHelper();
				paramsList.add(new BasicNameValuePair("username", helper.getUserName()));
				paramsList.add(new BasicNameValuePair("password", helper.getPassword()));
				clientId = PushManager.getInstance().getClientid(LoginActivity.this);			
				paramsList.add(new BasicNameValuePair("clientId", clientId));
			}else{//添加第三方登录传递数据
				httpPost = new HttpPost(
					ConfigProperties.proxyLoginUrl());
				paramsList.add(new BasicNameValuePair("uid", thirdCustomerInfo.getUid()));
				paramsList.add(new BasicNameValuePair("accessToken", thirdCustomerInfo.getAccessToken()));			
				paramsList.add(new BasicNameValuePair("proxyType", thirdCustomerInfo.getProxyType()+""));
//				UserHelper helper = new UserHelper();
//				paramsList.add(new BasicNameValuePair("username", helper.getUserName()));
//				paramsList.add(new BasicNameValuePair("password", helper.getPassword()));
				clientId = PushManager.getInstance().getClientid(LoginActivity.this);			
				paramsList.add(new BasicNameValuePair("clientId", clientId));
			}
			UrlEncodedFormEntity entity;			
			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				entity = new UrlEncodedFormEntity(paramsList, "utf-8");			
				httpPost.setEntity(entity);
				HttpResponse httpResponse = httpClient.execute(httpPost);
				//验证Http响应状态码
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					Log.d("响应", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
					//获取响应实体
					HttpEntity httpEntity = httpResponse.getEntity();
					//获取服务器返回的信息，转换为UTF-8编码的字符串
					if (httpEntity != null) {
						String res = EntityUtils.toString(httpEntity, Charset
								.forName("UTF-8").toString());
						data.putString("value", res);
						httpEntity.consumeContent();
					}
				}
			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_Login_Failure));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_Login_Failure));
					e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_Login_Failure));
					e.printStackTrace();			
			}finally {
				//发送message。关闭连接
				msg.what = GO_LOGIN;
				msg.setData(data);
				getCstTokenhandler.sendMessageDelayed(msg, 1500);
				httpClient.getConnectionManager().shutdown();
			} 	
		}
	};
    /**
     * 处理服务器返回结果
     */
	private Handler getCstTokenhandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);	
			switch(msg.what) {
				case MSG_AUTH_CANCEL: {
					//取消授权
					Toast.makeText(LoginActivity.this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
				} break;
				case MSG_AUTH_ERROR: {
					//授权失败
					Toast.makeText(LoginActivity.this, R.string.auth_error, Toast.LENGTH_SHORT).show();
				} break;
				case MSG_AUTH_COMPLETE: {
					//授权成功
					Toast.makeText(LoginActivity.this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
					Platform pf = (Platform) msg.obj;
//					Log.i("msg_id", msg.toString());
//					Log.i("msg_id", pf.getDb().getUserId()); //获取用户id
//					Log.i("msg_token", pf.getDb().getToken());//获取用户token
//					Log.i("msg_usename", pf.getDb().getUserName());//获取用户usename
//					Toast.makeText(LoginActivity.this, pf.getDb().getUserId(), Toast.LENGTH_SHORT).show();
//					Toast.makeText(LoginActivity.this, pf.getDb().getToken(), Toast.LENGTH_SHORT).show();
					MyApplication.getInstance().setUserId(pf.getDb().getUserName());
					thirdCustomerInfo.setUid(pf.getDb().getUserId());
					thirdCustomerInfo.setAccessToken(pf.getDb().getToken());
					
					login(true);//第三方登录
					
				} break;
				case GO_LOGIN: {
					Bundle data = msg.getData();
					String error = data.getString("Error");
					//关闭对话框
					pd.dismiss();
					if (error != null && !error.isEmpty()) {
						showToast(error);
						return;
					}
					//取出并处理JSON字符串
					String val = data.getString("value");
					try {
						JSONObject result = new JSONObject(val);
						
						//登录响应状态
						boolean isSuccess = result.getBoolean("success");
						if (isSuccess) {
//							//获取cstToken					
//							SharedPreferences preferences = getSharedPreferences(
//									SHAREDPREFERENCES_CUSTOMERINFO, Context.MODE_PRIVATE);
//							Editor editor = preferences.edit();
//							// 保存cstToken
//							editor.putString("cstToken", result.getString("cstToken"));
//							// 提交修改
//							editor.commit();
							MyApplication.getInstance().setCstToken(result.getString("cstToken"));
							
							if(null!=come){//如果从home界面过来，登录成功则setresult
				        		if(HOMEFRAGMENT.equals(come)){
				        			setResult(RESULT_OK);
				        		}
							}
//							if(null!=come){
//				        		if(ORDERFRAGMENT.equals(come)|| LOGOUT.equals(come)){
//				        			//跳转到HomeChangeActivity
//									Intent intent = new Intent();
//									intent.setClass(LoginActivity.this, HomeChangeActivity.class);
//									intent.putExtra("FragmentIndex", 1);
//									startActivity(intent);
//				        		}
//				        	}else{
//								Intent intent = new Intent();
//								intent.setClass(LoginActivity.this, HomeChangeActivity.class);
//								startActivity(intent);	
//				        	}
							
							LoginActivity.this.finish();
						} else {
							String message = result.getString("msg");
							showToast(message);
						}
					} catch(JSONException e) {	
						e.printStackTrace();
						showToast(getResources().getString(R.string.T_Login_Failure));
					} catch(Exception e){
						e.printStackTrace();
						showToast(getResources().getString(R.string.T_Login_Failure));
					}
				} break;
		   }
			
		}
	};
    

	private void initView(){      
        phoneNumber = (EditText) findViewById(R.id.edit_login_phone_number);
        resetPhoneNumber = (Button) findViewById(R.id.btn_reset_phone_number);
        passWord = (EditText) findViewById(R.id.edit_login_password);
        resetPassword = (Button) findViewById(R.id.btn_reset_password);
        passwordVisible = (Button) findViewById(R.id.btn_password_visible);
        login = (Button) findViewById(R.id.btn_Login);
        forgotPassword = (Button) findViewById(R.id.btn_forgot_password);
        weixinProxy = (Button) findViewById(R.id.btn_weixin_proxy);
        qqProxy = (Button) findViewById(R.id.btn_qq_proxy);
        weiboProxy = (Button) findViewById(R.id.btn_weibo_proxy);
        
        
    }
	

    /**
     * 初始化头部
     */
    @SuppressLint("ResourceAsColor") 
    private void initHeader(){
    	//头部半透明
    	RelativeLayout rl_head = (RelativeLayout) this.findViewById(R.id.login);
    	rl_head.setBackgroundColor(Color.argb(60, 0, 0, 0));
    	//注册返回按钮事件
		Button backBtn = (Button) findViewById(R.id.ivBack);
		backBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				if(null!=come){//如果从home界面过来，返回则setresult
	        		if(HOMEFRAGMENT.equals(come)){
	        			setResult(RESULT_OK);
	        		}
				}
				LoginActivity.this.finish();
			}
		});
		//设置Title文字为登录
		TextView center = (TextView) findViewById(R.id.tvTitle);
		center.setText(R.string.X_Login);
		//设置注册按钮  点击跳转到注册活动页面
		Button btnSignUp = (Button) findViewById(R.id.head_btnOperation);
		btnSignUp.setText(R.string.Sign_Up);
		btnSignUp.setVisibility(View.VISIBLE);
		btnSignUp.setOnClickListener(new OnClickListener(){

			@Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
                startActivityForResult(intent, REGIST_CODE);               
            }
        });		
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		//关闭shareSDK
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}
	//取消授权
	@Override
	public void onCancel(Platform arg0, int action) {
		// TODO Auto-generated method stub
		
			Message msg = new Message();
			msg.what = MSG_AUTH_CANCEL;
			getCstTokenhandler.sendMessage(msg);
		
	}
	//授权成功
	@Override
	public void onComplete(Platform platform, int action, HashMap<String, Object> arg2) {
		// TODO Auto-generated method stub
//			Log.i("msg1", platform.getDb().exportData().toString());
			Message msg = new Message();
			msg.what = MSG_AUTH_COMPLETE;
			msg.obj = platform;
			getCstTokenhandler.sendMessage(msg);
		
	}
	//授权失败
	@Override
	public void onError(Platform arg0, int action, Throwable t) {
		// TODO Auto-generated method stub
			
			Message msg = new Message();
			msg.what = MSG_AUTH_ERROR;
			getCstTokenhandler.sendMessage(msg);
		
			Log.i("msg", t.toString());
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(null!=come){//如果从home界面过来，返回则setresult
        		if(HOMEFRAGMENT.equals(come)){
        			setResult(RESULT_OK);
        		}
			}
			finish();
		}
		return false;
	}
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	switch (requestCode) { 
 	   	case REGIST_CODE:
 	   		if(resultCode == RESULT_OK){
	 	   		setResult(RESULT_OK);
	 	   		finish();
 	   		}
 	    break;
    	}
    	super.onActivityResult(requestCode, resultCode, data);
    }
}


